<template>
  <div class="admin-employees">
    <!-- 侧边栏 -->
    <AdminSidebar ref="sidebarRef" :class="{ collapsed: sidebarCollapsed }" />

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <!-- 顶部导航 -->
      <AdminHeader 
        page-title="员工管理"
        :sidebar-collapsed="sidebarCollapsed"
        @toggle-sidebar="toggleSidebar"
      />

      <!-- 内容区域 -->
      <div class="content">
        <el-card shadow="hover">
          <div class="card-header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon> 新增员工
            </el-button>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或姓名"
              prefix-icon="Search"
              class="search-input"
            >
              <template #append>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
            <el-select v-model="filterStatus" placeholder="员工状态" class="filter-select">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </div>

          <el-table
            :data="employees"
            style="width: 100%"
            border
            stripe
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="员工ID" width="80"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="adminLevel" label="管理员等级" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.adminLevel===0 ? 'warning' : 'info'">
                  {{ scope.row.adminLevel===0 ? '超级管理员' : '普通管理员' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <div class="status-container">
                  <el-tag :type="scope.row.status === '1' || scope.row.status === 1 ? 'success' : 'danger'"
                          class="status-tag">
                    {{ scope.row.status === '1' || scope.row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                  <el-switch :disabled="scope.row.adminLevel===0"
                      :model-value="scope.row.status === '1' || scope.row.status === 1"
                      @change="toggleStatus(scope.row)"
                      class="status-switch"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <!-- 不能编辑或删除自己 -->
                <el-button type="warning" text @click="editEmployee(scope.row)" :disabled="scope.row.id === adminInfo.id">
                  编辑
                </el-button>
                <el-button type="danger" text @click="deleteEmployee(scope.row)" :disabled="scope.row.id === adminInfo.id">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[5, 10, 15, 20]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 新增/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form :model="employeeForm" :rules="rules" ref="employeeFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="employeeForm.username" placeholder="请输入用户名" :disabled="!!currentEmployeeId"></el-input>
          <div class="form-hint" v-if="currentEmployeeId">用户名不可修改</div>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :required="!currentEmployeeId">
          <el-input v-model="employeeForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          <div class="form-hint" v-if="currentEmployeeId">不修改密码请留空</div>
        </el-form-item>
        <el-form-item label="员工状态" prop="status">
          <el-switch v-model="employeeForm.status" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="超级管理员" prop="isSuperAdmin" v-if="adminInfo.isSuperAdmin && !currentEmployeeId">
          <el-switch v-model="adminLevel"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'
import {addAdmins,adminsPage,adminsEdit,adminsDel} from "@/api/Admins.js";

const router = useRouter()
const sidebarCollapsed = ref(false)
const sidebarRef = ref()

// 管理员信息
const adminInfo = computed(() => {
  const info = localStorage.getItem('adminInfo')
  if (info) {
    return JSON.parse(info)
  }
  return { name: '管理员' }
})

const isSuperAdmin = computed(() => {
  const info = localStorage.getItem('adminInfo')
  if (info) {
    return JSON.parse(info).isSuperAdmin || true
  }
  return true
})

// 检查是否是超级管理员，不是则跳转到仪表盘
if (!isSuperAdmin.value) {
  ElMessage.warning('您没有权限访问此页面')
  router.push('/admin/dashboard')
}

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')

//总记录数
const total = ref(0)
// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 5

})

// 选中的员工
const selectedEmployees = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')
const currentEmployeeId = ref(null)
const employeeFormRef = ref(null)
//管理员等级
const adminLevel=ref(0)
// 表单数据
const employeeForm = reactive({
  username: '',
  name: '',
  password: '',
  status: '1',
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '姓名长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ]
}
// 模拟员工数据
const employees = ref([])
// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr ? new Date(dateStr).toLocaleString('zh-CN') : ''
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增员工'
  currentEmployeeId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑员工
const editEmployee = (employee) => {
  dialogTitle.value = '编辑员工'
  currentEmployeeId.value = employee.id
  Object.assign(employeeForm, {
    username: employee.username,
    name: employee.name,
    password: '', // 编辑时密码为空，不修改
    phone: employee.phone,
    email: employee.email,
    gender: employee.gender,
    status: employee.status
  })
  dialogVisible.value = true
}

// 删除员工
const deleteEmployee = (employee) => {
  if (employee.id === adminInfo.id) {
    ElMessage.warning('不能删除自己的账号')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除员工「${employee.name}」吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      // 模拟删除操作
      adminsDel(employee.id).then(res=>{
        if(res.code===200){
          queryPage()
          ElMessage.success("删除成功")
        }
      })
    })
    .catch(() => {
      // 取消删除
    })
}

// 切换员工状态
const toggleStatus = (admins) => {
  // 获取当前状态
  const currentStatus = admins.status
  // 切换状态值
  const newStatus = (currentStatus === '1' || currentStatus === 1) ? '0' : '1'
  // 更新用户状态
  admins.status = newStatus
  // 模拟API调用更新状态
  // updateStatus({"id":user.id,"status":user.status}).then(res=>{
  //   if(res.code===200){
  //     ElMessage.success(`用户${newStatus === '1' ? '启用' : '禁用'}成功`)
  //   }else{
  //     ElMessage.error(`用户${newStatus === '1' ? '启用' : '禁用'}失败`)
  //   }
  // })
}

// 重置表单
const resetForm = () => {
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
  Object.assign(employeeForm, {
    username: '',
    name: '',
    password: '',
    phone: '',
    email: '',
    gender: '保密',
    status: '1',
    isSuperAdmin: false
  })
  currentEmployeeId.value = null
}

// 提交表单
const submitForm =  () => {
  try {
     employeeFormRef.value.validate()
    
    if (currentEmployeeId.value) {
      console.log(currentEmployeeId.value)
      // 编辑操作
      adminsEdit({
        "id":currentEmployeeId.value,
        "name":employeeForm.name,
        "password":employeeForm.password,
       "status":employeeForm.status,
      }).then(res=>{
        if(res.code===200){
          ElMessage.success("编辑成功")
          queryPage()
        }else{
          ElMessage.error("编辑失败")
        }
      })
    } else {
      // 新增操作
      // 检查用户名是否已存在
      if (employees.value.some(emp => emp.username === employeeForm.username)) {
        ElMessage.error('用户名已存在')
        return
      }
      //发送异步添加请求
      addAdmins(employeeForm).then(res=>{
        if(res.code===200){
          ElMessage.success('新增成功')
        }else{
          ElMessage.error('新增失败')
        }
      })
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  selectedEmployees.value = selection
}
// 处理搜索
const handleSearch = () => {
  queryPage()
}
//分页查询
const queryPage=()=>{
  //发送异步请求
  adminsPage({
    "keyword": searchKeyword.value,
    "status": filterStatus.value,
    "curPage": pagination.currentPage,
    "pageSize": pagination.pageSize
  }).then(res=>{
    console.log(res)
      total.value = res.data.total
      pagination.currentPage = res.data.curPage
      pagination.pageSize = res.data.pageSize
      employees.value = res.data.dataList
  })
}
// 页容量处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  queryPage()

}
//当前页处理
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  queryPage()
}

// 检查登录状态
const checkLoginStatus = () => {
  const adminToken = localStorage.getItem('adminToken')
  if (!adminToken || !adminInfo.username) {
    ElMessage.error('请先登录')
    router.push('/admin/login')
  }
}

onMounted(() => {
  // checkLoginStatus()
  queryPage()
})
</script>

<style scoped>
.admin-employees {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

.main-content {
  flex: 1;
  margin-left: 250px;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  transition: margin-left 0.3s;
}

.main-content.sidebar-collapsed {
  margin-left: 64px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    margin-left: 200px;
  }
  
  .main-content.sidebar-collapsed {
    margin-left: 64px;
  }
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header-actions {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>